<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use app\common\model\Video as VideoModel;
use app\common\model\Like;
use app\common\model\VideoGroup;
use app\common\model\Follower;
use app\common\model\User;
use think\Lang;

/**
 * 接口
 */
class Video extends Api
{
    protected $noNeedLogin = ['list','videogroup','groupvideolist','videodetails','recommend','sort','uservideolist'];
    protected $noNeedRight = ['likezan','hasfollower','userfollower','userworks','userworksdel','uploadvideo','wolike','wodellike'];
    /**
     * [$userId 用户ID]
     * @var [type]
     */
    protected $userId = 0;
    protected $followerId = 0;
    /**
     * [_initialize 初始化]
     * @return [type] [description]
     */
    public function _initialize()
    {
        parent::_initialize();
        $islogin = $this->auth->islogin();
        if($islogin){
            $userinfo = $this->auth->getUserinfo();
            $this->userId = $userinfo['id'];
        }
        $Lang = Lang::load(APP_PATH . 'api/lang/zh-cn/user.php');
    }
    /**
     * [list 商家数据列表]
     * @author xiaoliu
     * @DateTime 2019-11-24T10:59:20+0800
     * @param    integer                  $offset [偏移量]
     * @param    integer                  $limit  [请求条数]
     * @param    string                   $filter [多关键字搜索(非模糊搜索)]
     * @param    string                   $search [模糊关键字搜索]
     * @param    string                   $sort   [排序字段名]
     * @param    string                   $order  [排序desc,asc]
     * @return   [json]                           [description]
     */
    public function list($offset = 1, $limit = 30, $filter = '{}', $search = '', $sort = 'id', $order = 'desc')
    {
        if ($limit > 100) {
            $limit = 100;
        }
        if(!$limit){
            $limit = 30;
        }
        $jsonStr = @stripslashes(html_entity_decode($filter));
        $jsonArr = @htmlspecialchars_decode($jsonStr, true);
        $json = json_decode($jsonArr,true);
        $where = [];
        $whereConcat = '';
        $and = '';
        $whereConcatc = '';
        $andc = '';
        foreach ($json as $key => $value) {
            if($key=='audit'||$key=='status'){
                continue;
            }
            if ($value != 'all' && $key != 'keyword' && $key != 'group_id') {
                $where[$key] = trim($value);
                continue;
            }
            if ($value != 'all') {
                if($key=='group_id'){
                    $exp = explode(',',$value);
                    $keyc = 'group_id';
                    foreach($exp as $value){
                        $whereConcatc .= $andc . "FIND_IN_SET('$value', $keyc)";
                        if ($whereConcatc != '') {
                            $andc = ' OR ';
                        }
                    }
                }else{
                    $whereConcat .= $and . "FIND_IN_SET('$value', $key)";
                    if ($whereConcat != '') {
                        $and = ' AND ';
                    }
                }
            }
            
        }
        $blurry = [];
        if ($search) {
            $blurry['name|keyword|brief'] = array('like', '%' . $search . '%');
        }
        $offset = intval($offset);
        $limit = intval($limit);
        $field = 'audit,status,remark,createtime,updatetime';
        $list = VideoModel::field($field, true)->where(['audit'=>1,'status'=>1])->with('Videogroup,User')->withCount('likenum')->where($whereConcatc)->order($sort . ' ' . $order)->where($where)->where($blurry)->where($whereConcat)->paginate($limit, false,
            [
                'page' => $offset,
            ])->toArray();
        $result = array("total" => $list['total'], "rows" => $list['data'], 'pagess' => $offset);
        $this->success('',$result);
    }

    /**
     * videogroup function
     * 视频分组
     * @Author XiaoLiu 528772568@qq.com
     * @DateTime 2020-05-31 15:35:20
     * @param integer $id
     * @return void
     */
    public function videogroup($id=0){
        $check = VideoGroup::where('id', $id)->where('status',1)->find();
        $list = [];
        if($check){
            $list = VideoGroup::where('pid', $id)->where('status',1)->select();
        }
        $this->success('',$list);
    }

    /**
     * Undocumented function
     *  (废弃接口)
     * @Author XiaoLiu 528772568@qq.com
     * @DateTime 2020-06-01 11:09:03
     * @param [type] $id
     * @param integer $limit
     * @param integer $offset
     * @return void
     */
    public function groupvideolist($id,$limit=10,$offset=1){
        $exp = explode(',',$id);
        $whereConcat = '';
        $and = '';
        $key = 'group_id';
        foreach($exp as $value){
            $whereConcat .= $and . "FIND_IN_SET('$value', $key)";
            if ($whereConcat != '') {
                $and = ' OR ';
            }
        }
        // foreach($exp as $value){
        //     $whereConcat .= $and . "CONCAT(',', group_id, ',') LIKE CONCAT('%,',$value, ',%')";
        //     if ($whereConcat != '') {
        //         $and = ' OR ';
        //     }
        // }

        $list = VideoModel::where(['audit'=>1,'status'=>1])->where($whereConcat)->paginate($limit, false,
        [
            'page' => $offset,
        ])->toArray();
        
        $result = array("total" => $list['total'], "rows" => $list['data'], 'pagess' => $offset);
        $this->success('',$result);
    }
    /**
     * Undocumented function
     * 视频详情
     * @Author XiaoLiu 528772568@qq.com
     * @DateTime 2020-06-02 18:34:34
     * @param [type] $id
     * @return void
     */
    public function videodetails($id){
        $list = VideoModel::where(['audit'=>1,'status'=>1])->with('Videogroup,User')->with(['like'=>function($query){
            $query->where('user_id',$this->userId);
        }])->withCount(['likenum'=>function($query)use($id){
            $query->where('video_id',$id);
        }])->find($id);
        
        if($list){
            VideoModel::where('id', $id)->setInc('playnum');
            $list['followercount_count'] = 0;
            $list['follower'] = 0;
            if(isset($list['user']['id'])){
                // $this->followerId = $list['user']['id'];
                // $follower = Follower::with(['follower'=>function($query){
                //     $query->where('user_id',$this->userId);
                // }])->withCount(['followercount'=>function($query){
                //     $query->where('form_id',$this->followerId);
                // }])->find($list['user']['id']);
                $list['followercount_count'] = Follower::where('form_id',$list['user']['id'])->count();
                $list['follower'] = Follower::where(['user_id'=>$this->userId,'form_id'=>$list['user']['id']])->find();
                if($list['follower']){
                    $list['follower']=1;
                }
            }
            // print_r();
            // ->withCount(['followercount'=>function($query){
            //     print_r($query);
            //     $query->where('form_id',$this->dataId);
            // }])
            $this->success('',$list);
        }
        $this->error('数据不存在!');
    }

    /**
     * Undocumented function
     * 点赞
     * @Author XiaoLiu 528772568@qq.com
     * @DateTime 2020-06-02 18:38:47
     * @param [type] $id
     * @return void
     */
    public function likezan($id){
        if (!$this->request->isPost()){
            $this->error(__('请求类型错误!'));
        }
        $arr = Like::where(['user_id'=>$this->userId,'video_id' => $id])->find();
        if($arr){
            Like::destroy($arr['id']);
            $this->success('取消成功',0);
        }else{
            Like::create(['user_id'=>$this->userId,'video_id' => $id]);
            $this->success('点赞成功',1);
        }
        $this->error('操作失败!');
    }

    /**
     * hasfollower function
     * 关注
     * @Author XiaoLiu 528772568@qq.com
     * @DateTime 2020-06-03 18:04:25
     * @param [type] $id
     * @return void
     */
    public function hasfollower($id){
        if (!$this->request->isPost()){
            $this->error(__('请求类型错误!'));
        }
        $check = User::where(['status'=>'normal','id'=>$id])->field('id,username,nickname,avatar,bio,gender')->find();
        
        if($check){
            $arr = Follower::where(['user_id'=>$this->userId,'form_id' => $check['id']])->find();
            if($arr){
                Follower::destroy($arr['id']);
                $this->success('取消成功',0);
            }else{
                Follower::create(['user_id'=>$this->userId,'form_id' => $check['id']]);
                $this->success('关注成功',1);
            }
        }
        
        $this->error('操作失败!');
    }

    /**
     * Undocumented function
     * 推荐视频
     * @Author XiaoLiu 528772568@qq.com
     * @DateTime 2020-06-03 17:09:12
     * @param string $value
     * @param integer $limit
     * @param integer $offset
     * @return void
     */
    public function recommend($that=0,$value='',$group=0,$limit=10,$offset=1){
        
        $exp = explode(',',$value);
        $thatwhere = '';
        if($that&&$that!=''){
            $thatwhere = 'id!='.$that;
        }
        $whereConcat = '';
        $and = '';
        $key = 'keyword';
        if($value){
            foreach($exp as $val){
                $whereConcat .= $and . "FIND_IN_SET('$val', $key)";
                if ($whereConcat != '') {
                    $and = ' OR ';
                }
            }
        }
        $list = VideoModel::where(['audit'=>1,'status'=>1])->where($whereConcat)->where($thatwhere)->with('Videogroup,User')->withCount('likenum')->paginate($limit, false,
        [
            'page' => $offset,
        ])->toArray();
        $num = $limit-count($list['data']);//count($list['data'])
        if($num!=0){
            $ispresence = '';
            $isand = '';
            foreach($list['data'] as $v){
                $ispresence.=$isand.'id!=' .$v['id'];
                $isand = ' and ';
            }
            $groupwhere = '';
            if($group){
                $groupwhere='group_id='.intval($group);
            }
            
            $push = VideoModel::where(['audit'=>1,'status'=>1])->where($ispresence)->where($thatwhere)->with('Videogroup,User')->whereOr($groupwhere)->withCount('likenum')->limit($num)->select();
            foreach($push as $i){
                array_push($list['data'],$i);
            }
        }
        $result = array("total" => $list['total'], "rows" => $list['data'], 'pagess' => $offset);
        $this->success('',$result);
    }

    /**
     * Undocumented function
     * 视频分组列表
     * @Author XiaoLiu 528772568@qq.com
     * @DateTime 2020-06-03 17:25:49
     * @return void
     */
    public function sort(){
        $arr = VideoGroup::where("status = 1 and pid!=0 and picurl!=''")->field('status,createtime,updatetime',true)->order('weigh DESC')->select();
        $this->success('',$arr);
    }

    /**
     * Undocumented function
     * 用户关注列表
     * @Author XiaoLiu 528772568@qq.com
     * @DateTime 2020-06-04 11:40:30
     * @return void
     */
    public function userfollower(){
        $arr = Follower::where('user_id',$this->userId)->with('follower')->select();
        foreach($arr as $key=>$val){
            if(!$val['follower']){
                unset($arr[$key]);
            }  
            $arr[$key]['followercount_count'] = Follower::where('form_id',$arr[$key]['follower']['id'])->count();
        }
        $this->success('',array_values($arr));
    }

    /**
     * Undocumented function
     * 用户作品列表
     * @Author XiaoLiu 528772568@qq.com
     * @DateTime 2020-06-05 15:25:08
     * @param integer $limit
     * @param integer $offset
     * @return void
     */
    public function userworks($limit=20,$offset=1){
        $list = VideoModel::where('user_id',$this->userId)->order('weigh DESC')->paginate($limit, false,
        [
            'page' => $offset,
        ])->toArray();
        $result = array("total" => $list['total'], "rows" => $list['data'], 'pagess' => $offset);
        $this->success('',$result);
    }

    /**
     * Undocumented function
     * 删除作品
     * @Author XiaoLiu 528772568@qq.com
     * @DateTime 2020-06-05 15:53:23
     * @param integer $id
     * @return void
     */
    public function userworksdel($id=0){
        $arr = VideoModel::where(['id'=>$id,'user_id'=>$this->userId])->delete();
        if($arr){
            $this->success('删除成功!');
        }
        $this->error('删除失败!');
    }
    /**
     * Undocumented function
     * 用户视频列表
     * @Author XiaoLiu 528772568@qq.com
     * @DateTime 2020-06-05 20:10:06
     * @param integer $id
     * @return void
     */
    public function uservideolist($id=0,$limit=20,$offset=1){
        $list = VideoModel::where(['status'=>1,'user_id'=>$id,'audit'=>1])->order('weigh DESC')->field('id,name,cover')->paginate($limit, false,
        [
            'page' => $offset,
        ])->toArray();
        $result = array("total" => $list['total'], "rows" => $list['data'], 'pagess' => $offset);
        $this->success('',$result);

    }
    /**
     * Undocumented function
     * 提交作品
     * @Author XiaoLiu 528772568@qq.com
     * @DateTime 2020-06-11 19:35:40
     * @return void
     */
    public function uploadvideo(){
        $arr = $this->request->only('name,group_id,keyword,cover,link,duration,size,width,height,brief');
        if(!isset($arr['name'])||$arr['name']==''){
            $this->error('请输入标题');
        }
        if(!isset($arr['group_id'])||$arr['group_id']==''){
            $this->error('请选择分类');
        }
        if(!isset($arr['link'])||$arr['link']==''){
            $this->error('请上传作品');
        }
        $arr['user_id']=$this->userId;
        $arr['remark']='小程序用户上传';
        if(!$arr['cover']){
            $time = 1;
            $size = '350x240';
            $dir = '/www/wwwroot/well.zmmz.com/wellvideo/public';
            $rootPath = ROOT_PATH . 'public';
            $dirs= '/uploads'.'/'.date("Ymd").'/';
            if (!file_exists($rootPath . $dirs)) {
                mkdir($rootPath . $dirs, 0777, true);
            }
            $fileName = uniqid().time().mt_rand(10000,99999);
            $cover = $dirs.'/'.$fileName.'.jpg';
            $str = "/monchickey/ffmpeg/bin/./ffmpeg -i ".$dir.$arr['link']." -y -f image2 -ss ".$time." -t 0.001 -s $size ".$dir.$cover;
            // image2
            exec($str,$out,$status);
            $arr['cover'] = $cover;
        }
        
        $save = VideoModel::create($arr);
        if($save){
            $this->success('提交成功!');
        }
        $this->error('提交失败!');
    }
    public function getVideoCover($file,$time,$dir,$size) {
        $time = $time ? $time : '1';      //默认截取第一秒第一帧
        $size = $size ? $size : '348*470';
        $fileName = 1;//getImgName();
     
        //临时视频路径，生成截图后删除
        $tempfiles = $dir.$fileName.'.mp4';
        $bool = move_uploaded_file($file, $tempfiles);
        $str = "ffmpeg -i ".$tempfiles." -y -f mjpeg -ss ".$time." -t 0.001 -s $size ".$dir.$fileName.'.jpg';
        exec($str,$out,$status);
        return $fileName;
    }
    /**
     * Undocumented function
     * 用户点赞列表
     * @Author XiaoLiu 528772568@qq.com
     * @DateTime 2020-06-12 10:55:42
     * @param integer $limit
     * @param integer $offset
     * @return void
     */
    public function wolike($limit=20,$offset=1){
        $list = Like::where('user_id',$this->userId)->order('id DESC')->with('video')->paginate($limit, false,
        [
            'page' => $offset,
        ])->toArray();
        $result = array("total" => $list['total'], "rows" => $list['data'], 'pagess' => $offset);
        $this->success('',$result);
    }

    /**
     * Undocumented function
     * 用户点赞列表
     * @Author XiaoLiu 528772568@qq.com
     * @DateTime 2020-06-12 15:14:49
     * @param integer $id
     * @return void
     */
    public function wodellike($id=0){
        $del = Like::where(['user_id'=>$this->userId,'id'=>$id])->delete();
        if($del){
            $this->success('删除成功!');
        }
        $this->error('删除失败!');
    }
}